//
//  PDDHomeViewController.m
//  PDDriver
//
//  Created by DH on 2016/11/29.
//  Copyright © 2016年 PD. All rights reserved.
//

#import "PDDHomeViewController.h"
#import "PDDHomeTableViewCell.h"
#import "PDDGoodTableViewCell.h"
#import "PDDFindTableViewCell.h"
#import "PDDMoreTableViewCell.h"


#import "PDDFMDBCollectionCell.h"



#import "AddressFMDBManager.h"
#import "ProvinceAddressModel.h"
#import "CityAddressModel.h"
#import "DistrictModel.h"




#import <CoreLocation/CoreLocation.h>




@interface PDDHomeViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,UICollectionViewDataSource,UICollectionViewDelegate>{

    UIButton *button;
    //省份数组
    NSMutableArray *province;
    //城市
    NSMutableArray *city;
    //区
    NSMutableArray *district;
    
    NSString *selectedProvince;
    //标记用户点击几次
    NSInteger   i;

    //数据库管理
    AddressFMDBManager *addFMDBManager;
    //用户判断用户第二次点击button时间 查询城市选择
    BOOL    someBool;

    }

//定位服务
@property(nonatomic,strong)CLLocationManager *locationManager;

//tablview视图
@property(nonatomic,strong) UITableView *tableView;
//左侧button
@property(nonatomic,strong) UIButton  *leftabButton;
//城市选择
@property(nonatomic,strong)UICollectionView *collectionview;
//记录城市选择的button
@property(nonatomic,strong)NSMutableArray *arrayone;


@end

@implementation PDDHomeViewController

#pragma mark 定位服务
-(void)locationupdate{
    //检测定位功能是否开启
    if([CLLocationManager locationServicesEnabled]){
        
        if(!_locationManager){
            
            self.locationManager = [[CLLocationManager alloc] init];
            
            if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
                [self.locationManager requestWhenInUseAuthorization];
                [self.locationManager requestAlwaysAuthorization];
                
            }
            
            //设置代理
            [self.locationManager setDelegate:self];
            //设置定位精度
            [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
            //开始定位
            [self.locationManager startUpdatingLocation];
       
        }
        
    }else{
      
         //没有看起定位操作
        
//        UIAlertController *alertiview = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有开启定位" preferredStyle:(UIAlertControllerStyleAlert)];
//        //创建按钮
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(
//UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//    
//      NSLog(@"知道了");
//        }];
//        // 注意取消按钮只能添加一个
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
//            // 点击按钮后的方法直接在这里面写
//            NSLog(@"我又知道了");
//        }];
//        
//    //添加按钮
//        [alertiview addAction:okAction];
//        [alertiview addAction:cancelAction];
//        
//    
//        [self presentViewController:alertiview animated:YES completion:nil];
//
//        
        
        
     }
}

//定位后调用的 代理方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    [self.locationManager stopUpdatingLocation];

    CLLocation* location = locations.lastObject;
    
    NSLog(@"纬度=%f，经度=%f",location.coordinate.latitude,location.coordinate.longitude);

    //根据经纬度反向地理编译出地址信息
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
       
        if (placemarks.count == 0 || error) {
           
            return ;
        }
        
        CLPlacemark  *placemarek  =  [placemarks firstObject];
        

        
        NSLog(@"%@",[NSString stringWithFormat:@"%@",placemarek.locality]);
        
        
        [self.leftabButton setTitle:placemarek.locality forState:UIControlStateNormal];
        
    }];
    
 
}



-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    if ([error code] == kCLErrorDenied){
        //访问被拒绝
    }
    if ([error code] == kCLErrorLocationUnknown) {
        //无法获取位置信息
    }
};




#pragma mark 自定义城市选择button
//自定义 navigationitem.leftbarbuttonitem

-(UIButton *)leftabrbuttonitem:(NSString *)text{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
     
     //修改图片颜色
     btn.tintColor = DHRGB(133, 140, 147);
     
     UIImage  *image =  [[UIImage imageNamed:@"555"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
     
     [btn setImage:image forState:UIControlStateNormal];
     
     
     [btn setTitle:text forState:UIControlStateNormal];
     
     [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
     
     
     btn.titleLabel.font =  [UIFont systemFontOfSize:13];
    
     [btn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:0.5];

    
    [btn  addTarget:self action:@selector(addcollcetion) forControlEvents:UIControlEventTouchDown];
    return btn;
  }



//添加城市选择
-(void)addcollcetion{

 
    [self collectionfly];
    
    
   

}

#pragma mark  创建城市选择
-(void)collectionfly{

    
    //用户第一次点击城市选择按钮
    if (self.collectionview == nil) {
        UICollectionViewFlowLayout *collectionfly = [[UICollectionViewFlowLayout alloc]init];
        
        collectionfly.minimumLineSpacing = 10;
        //定义每个UICollectionView 纵向的间距
        collectionfly.minimumInteritemSpacing = 5;
        //定义每个UICollectionView 的边距距
        collectionfly.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);//上左下右
        
        NSInteger with = ([UIScreen mainScreen].bounds.size.width-60) / 4;
        
        NSInteger height = [UIScreen mainScreen].bounds.size.height /20;
        
        
        collectionfly.itemSize = CGSizeMake(with, height);
        
        self.collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 400)collectionViewLayout:collectionfly];
        
        
        self.collectionview.delegate =self;
        
        self.collectionview.dataSource = self;
        
        [self.collectionview registerClass:[PDDFMDBCollectionCell class] forCellWithReuseIdentifier:@"UICollectionCell"];
        
        [self.view addSubview: self.collectionview];
        
        self.collectionview.backgroundColor =[UIColor whiteColor];
        
       
            button = [UIButton buttonWithType: 100];
            [button setTitle: @"测试效果" forState: UIControlStateNormal];
            [button setFrame: CGRectMake(160-button.bounds.size.width/2, 500, button.bounds.size.width, button.bounds.size.height)];
            [button setTintColor: [UIColor grayColor]];
            [button addTarget: self action: @selector(buttobClicked:) forControlEvents: UIControlEventTouchUpInside];
            [self.view addSubview: button];

   
       
        
        
        [self fmdb];
        
        
    }
    
    //用户第二次点击城市选择按钮
    else{
        

        someBool = NO;

        self.collectionview.frame =CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 400);
        
        
        button.frame = CGRectMake(100, 500, 200, 100);
        
        
        //得到省份的model数组

        [self arraymutablearray:province];
        
        [self.collectionview reloadData];
        

        

        
    }
    
}



#pragma  mark  在数据库中获取数据
-(void)fmdb{
    
    province=[[NSMutableArray alloc] initWithCapacity:5];
    city=[[NSMutableArray alloc] initWithCapacity:5];
    district=[[NSMutableArray alloc] initWithCapacity:5];
    
    addFMDBManager=[AddressFMDBManager sharedAddressFMDBManager];
    
    //得到省份的model数组
    NSArray *arr=[NSArray arrayWithArray:[addFMDBManager selectAllProvince]];
    for (ProvinceAddressModel *provinceModel in arr) {
        [province addObject:provinceModel.name];
    }
    
    
    [self arraymutablearray:province];
    

    }

//添加最新数据
-(NSMutableArray *)arraymutablearray:(NSMutableArray*)array{
    
    if (self.arrayone == nil) {
        
        self.arrayone = [[NSMutableArray alloc]init];
        
        i = 1;
        
        [_arrayone addObjectsFromArray:array];
    }
    else{
        
        
        [self.arrayone removeAllObjects];
        if (someBool == NO) {
            
            
            NSLog(@"%@",someBool?@"yes":@"no");
            
            i = 1;
       
            
            [self.arrayone  removeAllObjects];

            [_arrayone addObjectsFromArray:array];
        }
        
        
        else {
    
            i = 2;
            [self.arrayone  removeAllObjects];

            
            [_arrayone addObjectsFromArray:array];
            
  
        }
    
    }
    
    
    return  _arrayone.copy;
    
    
}





-(void)buttobClicked:(UIButton *)btn{
    
    
    self.collectionview.frame = CGRectMake(0, 0, 0, 0);

    
    button.frame = CGRectMake(0, 0, 0, 0);
    
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

  
    //定位
    [self locationupdate];
    
    
    self.leftabButton =  [self leftabrbuttonitem:nil];
    
   
    self.leftabButton.frame =CGRectMake(100, 0, 100, 44);
    
    UIBarButtonItem  *menbutton = [[UIBarButtonItem alloc]initWithCustomView:self.leftabButton];
    
    [self.navigationItem setLeftBarButtonItem:menbutton];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:SCREEN_RECT style:UITableViewStyleGrouped];
    self.tableView.frame = SCREEN_RECT;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:self.tableView];
    
    //隐藏滑动条
    self.tableView.showsVerticalScrollIndicator = NO;
    
    }




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark tableView 代理方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 3 ;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        
        return  1 ;
    }
    else if(section == 1){
        
        
        return  3;
    }
    return 4;

}


-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *ruseIdentOne = @"setCellOne";
    static NSString *ruseIdentTwo = @"setCellTwo";
    static NSString *ruseIdentThere = @"setCellThere";
    
    if (indexPath.section == 0) {
        PDDHomeTableViewCell *cell =  [PDDHomeTableViewCell mainbasictableviewcell:tableView withrueseid:ruseIdentOne andindexpath:indexPath];
        

        return cell;
 
    }
 
    
#pragma mark  中间的组cell

    
    else if(indexPath.section ==1 ){
    
        
        
        if (indexPath.row == 0) {
            
            
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"a"];
            
           
            cell.textLabel.text = @"最新货源";
            
            return cell;
            
            
        }
        else if(indexPath.row == 1){
            PDDGoodTableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:ruseIdentTwo];
            
            if (cell == nil) {
                
                NSArray *nibss = [[NSBundle mainBundle]loadNibNamed:@"PDDGoodCell" owner:nil options:nil];
                
                cell = [nibss lastObject];
                
            }
            
            return  cell ;
        }
        
        
        PDDMoreTableViewCell *cell = [[PDDMoreTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"b"];
        
        
        
        return cell;
        
        
        
    }
    
#pragma mark  最下面的组cell
   
    
    if (indexPath.row == 0) {
        
        
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"c"];
        
        cell.textLabel.text = @"发现";
        
        return cell;
        
        
    }
    

    
    PDDFindTableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:ruseIdentThere];
    
    if (cell == nil) {
        
        NSArray *nibss = [[NSBundle mainBundle]loadNibNamed:@"PDDFindCell" owner:nil options:nil];
        
        cell = [nibss lastObject];
        
    }
    
    return  cell ;

    
  }

#pragma mark 返回行高
-(CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section ==0){
        return 160;
    }
    
     else if(indexPath.section==1){
         
         
         switch (indexPath.row) {
             case 0:
                 return 40;
                 break;
                 
             case 1:
                 return 200;
                 
                 break;
                 
             default:
                 return 40;
                 break;
         }
         
         
        
     }
  
     else{
     
         switch (indexPath.row) {
             case 0:
                 return 40;
                 break;
                 
            
             default:
                 return 89;
                 break;
         }
      }
}


#pragma mark  禁止下拉 允许上提
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.tableView.contentOffset.y <= 0) {
        self.tableView.bounces = NO;
        
     

        
        //NSLog(@"禁止下拉");
    }
    else
        if (self.tableView.contentOffset.y >= 0){
            self.tableView.bounces = YES;
           // NSLog(@"允许上拉");
       
            

        }
    

    
}


//头视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  
    if (section == 0) {
        return 0.1;
    }
    
    return  20;
}




#pragma mark  CollectionView 的代理方法

-(NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    
    return 1;
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    //_arrayone.copy
    
    return [_arrayone count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdetifier =@"UICollectionCell";
    
    
    PDDFMDBCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdetifier forIndexPath:indexPath];
    
    
    cell.backgroundColor = DHRGB(241, 241, 241);
    
    cell.Celllable.text = [_arrayone objectAtIndex:indexPath.row];
    
   return cell;
  }


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (i == 1) {
        
        someBool = YES;
        
        
        [city removeAllObjects];
        //得到市的model的数组
        NSArray *arr2=[NSArray arrayWithArray:[addFMDBManager selectAllCityFrom:indexPath.row+1]];
        
        for (CityAddressModel *cityModel in arr2) {
            [city addObject:cityModel.name];
        
        }
        
        [self arraymutablearray:city];
        
        [collectionView reloadData];
        

        

        
    }
    
    else if ( i == 2){
        

        
        [district removeAllObjects];
      
        //获取当前cell内容
        PDDFMDBCollectionCell *cell = (PDDFMDBCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        

        NSUInteger  j =[addFMDBManager  selectIdFromCityWith:cell.Celllable.text];
        
        
        NSLog(@"%lu",(unsigned long)j);
        
        //得到区的model的数组
        
        
        NSArray *arr3=[NSArray arrayWithArray:[addFMDBManager selectAllDistrictFrom:j]];
        
        
        for (DistrictModel *districtModel in arr3) {
            [district addObject:districtModel.name];
            
            NSLog(@"%@",districtModel.name);
            
            
        }
        
        
        [self arraymutablearray:district];
        
        [collectionView reloadData];
        
    
        i = 0;
    }
    
   

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
